package com.cygsunri.util;

import javax.crypto.Mac;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.io.UnsupportedEncodingException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;

public class HMACUtil {

    /**
     * MAC算法可选以下多种算法
     * <p>
     * HmacMD5
     * HmacSHA1
     * HmacSHA256
     * HmacSHA384
     * HmacSHA512
     */

    public static String hmacDigestMD5(String msg, String keyString) {
        return hmacDigest(msg, keyString, "HmacMD5");
    }

    public static String hmacDigestSHA1(String msg, String keyString) {
        return hmacDigest(msg, keyString, "HmacSHA1");
    }

    public static String hmacDigestSHA256(String msg, String keyString) {
        return hmacDigest(msg, keyString, "HmacSHA256");
    }

    public static String hmacDigestSHA384(String msg, String keyString) {
        return hmacDigest(msg, keyString, "HmacSHA384");
    }

    public static String hmacDigestSHA512(String msg, String keyString) {
        return hmacDigest(msg, keyString, "HmacSHA512");
    }

    private static String hmacDigest(String msg, String keyString, String keyMac) {
        String digest = null;
        try {
            SecretKeySpec key = new SecretKeySpec((keyString).getBytes("UTF-8"), keyMac);
            Mac mac = Mac.getInstance(keyMac);
            mac.init(key);

            byte[] bytes = mac.doFinal(msg.getBytes("UTF-8"));

            StringBuffer hash = new StringBuffer();
            for (byte b : bytes) {
                String hex = Integer.toHexString(0xFF & b);
                if (hex.length() == 1) {
                    hash.append('0');
                }
                hash.append(hex);
            }
            digest = hash.toString();
        } catch (UnsupportedEncodingException | InvalidKeyException | NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return digest;
    }

}